package com.vehicle.repair.controller;

import com.vehicle.repair.model.MaterialUsage;
import com.vehicle.repair.service.MaterialService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/materials")
public class MaterialController {
    private final MaterialService materialService;

    public MaterialController(MaterialService materialService) {
        this.materialService = materialService;
    }

    @PostMapping
    public ResponseEntity<MaterialUsage> addMaterialUsage(@RequestBody MaterialUsage materialUsage,
                                                       @RequestParam Integer orderId) {
        try {
            MaterialUsage savedUsage = materialService.addMaterialUsage(materialUsage, orderId);
            return ResponseEntity.ok(savedUsage);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<MaterialUsage> getMaterialUsageById(@PathVariable Integer id) {
        Optional<MaterialUsage> usage = materialService.getMaterialUsageById(id);
        return usage.map(ResponseEntity::ok)
                  .orElseGet(() -> ResponseEntity.notFound().build());
    }

    @GetMapping("/order/{orderId}")
    public ResponseEntity<List<MaterialUsage>> getMaterialUsagesByOrder(@PathVariable Integer orderId) {
        try {
            List<MaterialUsage> usages = materialService.getMaterialUsagesByOrder(orderId);
            return ResponseEntity.ok(usages);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.notFound().build();
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteMaterialUsage(@PathVariable Integer id) {
        materialService.deleteMaterialUsage(id);
        return ResponseEntity.noContent().build();
    }
}
